package com.huluobo.kotlinim2006a.contract.add

import android.util.Log
import com.huluobo.kotlinim2006a.data.AddFriendItem
import com.huluobo.kotlinim2006a.db.IMDatabase
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

/**
 * Created by lc on 2023/2/6.
 */
class AddFriendPresenter(private val view: AddFriendContract.View) : AddFriendContract.Presenter {
    val addFriendItems = mutableListOf<AddFriendItem>()
    override fun search(key: String) {
        doAsync {
            try {
                //在公司项目中,正常需要向公司自己的服务器发起请求,获取所有的用户列表
                //因为咱们没有自己的服务器,所以模拟一下这个过程,向环信请求好友列表来对比
                val userNames = EMClient.getInstance().contactManager().allContactsFromServer
                val allContacts = IMDatabase.instance.getAllContacts()
                userNames.forEach {
                    //对比是否已经添加好友
                    var isAdded = false
                    for (contact in allContacts) {
                        if (contact.name == it) {
                            isAdded = true
                        }
                    }
                    val addFriendItem = AddFriendItem(it, isAdded)
                    addFriendItems.add(addFriendItem)
                }

                runOnUIThread {
                    view.onSearchSuccess()
                }
            } catch (e: HyphenateException) {
                runOnUIThread {
                    view.onSearchFailed()
                    Log.i("TagA", "e:${e.message},code:${e.errorCode}")
                }
            }
        }
    }
}